package ms.unicorn.language.scoping;

import static org.eclipse.xtext.common.types.TypesPackage.Literals.JVM_CONSTRUCTOR;
import static org.eclipse.xtext.common.types.TypesPackage.Literals.JVM_TYPE;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.EcoreUtil2;
import org.eclipse.xtext.common.types.xtext.AbstractTypeScopeProvider;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.scoping.IScope;

import com.google.common.base.Predicate;
import com.google.inject.Inject;

public class UnicornJvmGlobalScopeProvider extends UnicornGlobalScopeProvider {
	@Inject
	private AbstractTypeScopeProvider typeScopeProvider;

	@Override
	public IScope getScope(Resource resource, EReference reference, Predicate<IEObjectDescription> filter) {
		IScope parentTypeScope = getParentTypeScope(resource, reference, filter, reference.getEReferenceType());
		return super.getScope(parentTypeScope, resource, false, reference.getEReferenceType(), filter);
	}

	protected IScope getParentTypeScope(Resource resource, EReference reference, Predicate<IEObjectDescription> filter,
			EClass referenceType) {
		IScope parentTypeScope = IScope.NULLSCOPE;
		if (EcoreUtil2.isAssignableFrom(JVM_TYPE, referenceType) || EcoreUtil2.isAssignableFrom(JVM_CONSTRUCTOR, referenceType)) {
			parentTypeScope = typeScopeProvider.getScope(resource, reference, filter);
		}
		return parentTypeScope;
	}
}
